﻿using Microsoft.EntityFrameworkCore;
using MyMes.Infrastructure;
using MyMES.IServices.Equipments;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Extensions;
using VOL.Core.Utilities.Response;
using VOL.Entity.DomainModels.Equipment;

namespace MyMES.Services.Equipments
{
    /// <summary>
    /// 设备类型服务类，提供设备类型相关的业务操作
    /// </summary>
    public class EquipmentTypeService : IEquipmentTypeService
    {
        private readonly IBaseRepository<EquipmentType> _equipmentTypeRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="equipmentTypeRepository">设备类型仓储接口</param>
        public EquipmentTypeService(IBaseRepository<EquipmentType> equipmentTypeRepository)
        {
            _equipmentTypeRepository = equipmentTypeRepository;
        }

        /// <summary>
        /// 添加设备类型
        /// </summary>
        /// <param name="equipmentType">设备类型实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> AddEquipmentType(EquipmentType equipmentType)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                // 保存数据
                await _equipmentTypeRepository.AddAsync(equipmentType);
                return response.OK("添加设备类型成功");
            }
            catch (Exception ex)
            {
                return response.Error($"添加设备类型失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除设备类型
        /// </summary>
        /// <param name="id">设备类型ID</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> DelEquipmentTypes(int id)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                // 获取要删除的设备类型的编码
                var equipmentType = await _equipmentTypeRepository.GetAll()
                    .FirstOrDefaultAsync(e => e.Id == id);
                
                if (equipmentType == null)
                {
                    return response.Error("未找到要删除的设备类型");
                }

                string equipmentCode = equipmentType.EquipmentCode;
                
                // 检查是否有子类型
                var childExists = await _equipmentTypeRepository.GetAll()
                    .AnyAsync(x => x.ParentCode == equipmentCode);

                // 执行删除，包括子类型
                if (childExists)
                {
                    // 递归获取所有子类型ID
                    var allTypesToDelete = new List<int> { id };
                    var allTypes = await _equipmentTypeRepository.GetAll().ToListAsync();
                    
                    GetAllChildrenIds(allTypes, equipmentCode, allTypesToDelete);
                    
                    // 删除所有相关类型
                    Expression<Func<EquipmentType, bool>> expression = e => allTypesToDelete.Contains(e.Id);
                    int result = await _equipmentTypeRepository.DelAll(expression);

                    if (result > 0)
                    {
                        return response.OK($"成功删除{result}条记录（包含子类型）");
                    }
                    else
                    {
                        return response.Error("删除失败");
                    }
                }
                else
                {
                    // 没有子类型，直接删除
                    Expression<Func<EquipmentType, bool>> expression = e => e.Id == id;
                    int result = await _equipmentTypeRepository.DelAll(expression);

                    if (result > 0)
                    {
                        return response.OK($"成功删除{result}条记录");
                    }
                    else
                    {
                        return response.Error("删除失败");
                    }
                }
            }
            catch (Exception ex)
            {
                return response.Error($"删除设备类型失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 递归获取所有子类型ID
        /// </summary>
        /// <param name="allTypes">所有类型列表</param>
        /// <param name="parentCode">父类型编码</param>
        /// <param name="result">结果集合</param>
        private void GetAllChildrenIds(List<EquipmentType> allTypes, string parentCode, List<int> result)
        {
            var children = allTypes.Where(x => x.ParentCode == parentCode).ToList();
            foreach (var child in children)
            {
                if (child == null) continue;
                
                if (!result.Contains(child.Id))
                {
                    result.Add(child.Id);
                }
                
                GetAllChildrenIds(allTypes, child.EquipmentCode, result);
            }
        }

        /// <summary>
        /// 获取设备类型列表
        /// </summary>
        /// <param name="typeName">设备类型名称（可选）</param>
        /// <param name="status">状态（可选）</param>
        /// <returns>操作结果，包含设备类型列表</returns>
        public async Task<WebResponseContent> GetEquipmentTypes(string? typeName, int? status)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                // 构建查询条件
                var query = _equipmentTypeRepository.GetAll();

                // 应用筛选条件
                query = query.WhereIF(!string.IsNullOrEmpty(typeName), x => x.EquipmentName.Contains(typeName));
                query = query.WhereIF(status.HasValue, x => x.Status == status.Value);

                // 获取所有数据
                var allTypes = await query.ToListAsync();

                // 构建树形结构数据
                var rootTypes = allTypes.Where(x => string.IsNullOrEmpty(x.ParentCode)).ToList();
                var result = new List<EquipmentTypeTreeModel>();

                foreach (var rootType in rootTypes)
                {
                    var treeNode = new EquipmentTypeTreeModel
                    {
                        Id = rootType.Id,
                        EquipmentCode = rootType.EquipmentCode ?? "",
                        EquipmentName = rootType.EquipmentName ?? "",
                        Status = rootType.Status,
                        Descs = rootType.Descs ?? "",
                        ParentCode = rootType.ParentCode ?? "",
                        Children = GetChildrenNodes(allTypes, rootType.EquipmentCode)
                    };
                    result.Add(treeNode);
                }

                return response.OK("获取成功", result);
            }
            catch (Exception ex)
            {
                return response.Error($"获取设备类型列表失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 递归获取子节点
        /// </summary>
        private List<EquipmentTypeTreeModel> GetChildrenNodes(List<EquipmentType> allTypes, string parentCode)
        {
            if (string.IsNullOrEmpty(parentCode))
            {
                return new List<EquipmentTypeTreeModel>();
            }
            
            var children = allTypes.Where(x => x.ParentCode == parentCode).ToList();
            var result = new List<EquipmentTypeTreeModel>();

            foreach (var child in children)
            {
                if (child == null) continue;
                
                var treeNode = new EquipmentTypeTreeModel
                {
                    Id = child.Id,
                    EquipmentCode = child.EquipmentCode ?? "",
                    EquipmentName = child.EquipmentName ?? "",
                    Status = child.Status,
                    Descs = child.Descs ?? "",
                    ParentCode = child.ParentCode ?? "",
                    Children = GetChildrenNodes(allTypes, child.EquipmentCode)
                };
                result.Add(treeNode);
            }

            return result;
        }

        /// <summary>
        /// 更新设备类型
        /// </summary>
        /// <param name="equipmentType">设备类型实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdEquipmentType(EquipmentType equipmentType)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                // 验证数据
                if (equipmentType == null)
                {
                    return response.Error("更新数据不能为空");
                }
                
                if (string.IsNullOrEmpty(equipmentType.EquipmentCode))
                {
                    return response.Error("设备类型编码不能为空");
                }

                if (string.IsNullOrEmpty(equipmentType.EquipmentName))
                {
                    return response.Error("设备类型名称不能为空");
                }
                
                // 检查记录是否存在
                Expression<Func<EquipmentType, bool>> expression = x => x.Id == equipmentType.Id;
   
               
                // 更新数据
                await _equipmentTypeRepository.UpdateAsync(equipmentType);
                return response.OK("更新设备类型成功");
            }
            catch (Exception ex)
            {
                return response.Error($"更新设备类型失败：{ex.Message}");
            }
        }
    }

    /// <summary>
    /// 设备类型树形结构模型
    /// </summary>
    public class EquipmentTypeTreeModel : EquipmentType
    {
        /// <summary>
        /// 子节点
        /// </summary>
        public List<EquipmentTypeTreeModel> Children { get; set; } = new List<EquipmentTypeTreeModel>();
    }
}
